/*
 * LZXTemplate.java July 2009
 *
 * Copyright (C) 2009, Quirino Zagarese <quirino@laszloitalia.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */
package org.eu4ria.tools.lzstubs;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Hashtable;

public class LZXTemplate {

	private static Hashtable<String, String> templates = new Hashtable<String, String>();

	private Hashtable<String, String> attributes = new Hashtable<String, String>();

	private String body = "";

	public LZXTemplate(String fileName, InputStream inputStream)
			throws Exception {
		String fileContent = templates.get(fileName);
		if (fileContent == null) {

			BufferedReader br = new BufferedReader(new InputStreamReader(
					inputStream));
			String line = br.readLine();
			while (line != null) {
				body = body + line + "\n";
				line = br.readLine();
			}
			templates.put(fileName, body);
		} else {
			body = new String(fileContent);
		}
	}

	public void setAttribute(String name, String value) {
		attributes.put(name, value);
	}

	public String getAttribute(String name) {
		return attributes.get(name);
	}

	public String getResult() {
		String result = body;
		Enumeration<String> attrs = attributes.keys();
		while (attrs.hasMoreElements()) {
			String attribute = attrs.nextElement();
			result = replaceAttribute(result, "$" + attribute, attributes
					.get(attribute));
		}
		return result;
	}

	private String replaceAttribute(String source, String attrName,
			String attrValue) {
		int stringIndex = 0;
		int currIndex = 0;
		int inc = attrName.length();
		String result = "";
		stringIndex = source.indexOf(attrName, currIndex);
		while (stringIndex != -1) {
			result = result + source.substring(currIndex, stringIndex)
					+ attrValue;
			currIndex = stringIndex + inc;
			stringIndex = source.indexOf(attrName, currIndex);
		}
		result = result + source.substring(currIndex);
		return result;
	}

}
